package com.bsj.power.pls.action;

import com.bsj.consumerQ.until.ExceptionUntil;
import com.bsj.power.common.config.cached.RedisCached;
import com.bsj.power.common.config.redis.RedisConstant;
import com.bsj.power.common.constant.NumericalConstants;
import com.bsj.power.common.util.SpringUtil;
import com.bsj.power.pls.config.cached.HighRiseCached;
import com.bsj.power.pls.config.net.netty.common.timer.ScheduledResetThread;
import com.bsj.power.pls.config.net.netty.gpgga.GpggaTcpClientConstant;
import com.bsj.power.pls.config.net.netty.gpgga.GpggaTcpClientNet;
import com.bsj.power.pls.file.AllDataFileUntil;
import com.bsj.power.pls.handle.CTDataQueue;
import com.bsj.power.pls.handle.WebSocketClientHandle;
import com.bsj.power.pls.initialize.PanelInitialize;
import com.bsj.power.pls.queue.AllQueueUntil;
import com.bsj.power.pls.queue.service.QueueService;
import com.bsj.power.pls.queue.service.impl.tactic.SequentialConsumeQueue;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.LinkedList;
import java.util.List;

/**
 * @author LiJiaXin
 * @version 1.0.0
 * @description Action
 * @time 2024/5/21 16:38
 */
@Component
@Slf4j
public class Action implements CommandLineRunner {

    List<QueueService> list = new LinkedList<>();

    List<GpggaTcpClientNet> gpggaTcpClientNets = new LinkedList<>();

//    @Autowired
//    private UdpUntil udpUntil;

    @Autowired
    private WebSocketClientHandle webSocketClientHandle;

//    @Autowired
//    private WebsocketService websocketService;

    @Value("${myUrl.wsUrl}")
    private String wsUrl;

    @Value("${runService}")
    private String runServiceBean;

    @Value("${myUrl.rtk.sleep}")
    private Integer sleep;

    @Value("${gpgga.unitOne.lon}")
    private double unitOneLon;

    @Value("${gpgga.unitOne.lat}")
    private double unitOneLat;

    @Value("${gpgga.unitOne.alt}")
    private double unitOneAlt;

    @Value("${gpgga.unitTwo.lon}")
    private double unitTwoLon;

    @Value("${gpgga.unitTwo.lat}")
    private double unitTwoLat;

    @Value("${gpgga.unitTwo.alt}")
    private double unitTwoAlt;


    @Autowired
    private AllQueueUntil allQueueUntil;

    @Autowired
    private AllDataFileUntil allDataFileUntil;

    @Autowired
    private PanelInitialize panelInitialize;

    @Autowired
    private RedisCached redisCached;

    @Override
    public void run(String... args) throws Exception {
        HighRiseCached highRiseCached = new HighRiseCached();
        highRiseCached.start();
        allQueueUntil.start();
        if (StringUtils.isNotEmpty(runServiceBean)) {
            String[] beanSplit = runServiceBean.split(";");
            for (String bean : beanSplit) {
                Object beanService = SpringUtil.getBean(bean);
                if (beanService instanceof QueueService) {
                    QueueService runService = (QueueService) beanService;
                    runService.init();
                    list.add(runService);
                } else {
                    log.warn("无法识别的业务名称:" + bean);
                }
            }
        }
//        TcpSerUntil tcpSerUntil = new TcpSerUntil();
//        tcpSerUntil.init(9200, );
//        udpUntil.init();
        allDataFileUntil.init();
//        websocketService.start();
        // todo 暂时不连
        webSocketClientHandle.start(wsUrl);

        log.info("<=====>mqtt分流队列启动<=====>");
        CTDataQueue.start();

//        TcpClientNet tcpClientNet = new TcpClientNet(RTKTcpClientConstant.ip, RTKTcpClientConstant.port);
//        tcpClientNet.initClient();
//        tcpClientNet.doConnect();
        ScheduledResetThread scheduledResetThread = new ScheduledResetThread();
        scheduledResetThread.doStart();
        //依次广播RTK数据线程
        SequentialConsumeQueue sequential = new SequentialConsumeQueue();
        sequential.doStart(sleep);
//        FusionDataConsume fusionData = new FusionDataConsume();
//        fusionData.doStart();
        panelInitialize.initialize();

        //GPGGA tcp连接初始化
        gpggaTcpClientNetStart();
    }

    @PreDestroy
    public void destroy() {
        log.info("<=====>mqtt分流队列停止<=====>");
        CTDataQueue.stop();

        allQueueUntil.stop();
        SequentialConsumeQueue sequential = new SequentialConsumeQueue();
        sequential.doStop();
//        FusionDataConsume fusionData = new FusionDataConsume();
//        fusionData.doStop();
//        udpUntil.stop();
        webSocketClientHandle.stop();
        try {
            list.stream().forEach(runService -> {
                runService.stop();
            });
        } catch (Exception e) {
            log.error("关闭错误:" + ExceptionUntil.getErrorStr(e));
        }
        ScheduledResetThread scheduledResetThread = new ScheduledResetThread();
        scheduledResetThread.doStop();
        gpggaTcpClientNetStop();
    }

    /**
     * GPGGA tcp连接初始化
     *
     * @return void
     * @author ljx
     * @time 2024/11/28 14:22
     */
    private void gpggaTcpClientNetStart() {
        //每次服务启动重新设置形变量
        String shapeVariable = unitOneLon + "," + unitOneLat + "," + unitOneAlt;
        redisCached.set(RedisConstant.SHAPE_VARIABLE_INFO_KEY + NumericalConstants.ONE, shapeVariable);
        GpggaTcpClientNet tcpClientNetOne = new GpggaTcpClientNet(GpggaTcpClientConstant.unitOneIp, GpggaTcpClientConstant.unitOnePort, NumericalConstants.ONE);
        tcpClientNetOne.initClient();
        tcpClientNetOne.doConnect();
        gpggaTcpClientNets.add(tcpClientNetOne);

        shapeVariable = unitTwoLon + "," + unitTwoLat + "," + unitTwoAlt;
        redisCached.set(RedisConstant.SHAPE_VARIABLE_INFO_KEY + NumericalConstants.TWO, shapeVariable);
        GpggaTcpClientNet tcpClientNetTwo = new GpggaTcpClientNet(GpggaTcpClientConstant.unitTwoIp, GpggaTcpClientConstant.unitTwoPort, NumericalConstants.TWO);
        tcpClientNetTwo.initClient();
        tcpClientNetTwo.doConnect();
        gpggaTcpClientNets.add(tcpClientNetTwo);
    }

    /**
     * GPGGA tcp连接停止
     *
     * @return void
     * @author ljx
     * @time 2024/11/28 14:28
     */
    private void gpggaTcpClientNetStop() {
        gpggaTcpClientNets.forEach(item -> {
            item.stop();
        });
    }

}
